package com.qf.lja.servlet;

import com.qf.lja.dao.AddrDao;
import com.qf.lja.dao.CartDao;
import com.qf.lja.dao.ProductDao;
import com.qf.lja.enity.Address;
import com.qf.lja.enity.Cart;
import com.qf.lja.enity.Product;
import com.qf.lja.enity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@WebServlet(urlPatterns = "/dPu")
public class DirectPurchaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        //字符集
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
//
//        //判断是否登录
//        HttpSession session = req.getSession();
//        User user = (User) session.getAttribute("user");
//
//        if (user == null) {
//            System.out.println("user null");
//            req.getRequestDispatcher("/login.jsp").forward(req, resp);
//        }
//
//        //
//        Integer productId = Integer.parseInt(req.getParameter("productId"));
//        Integer userId = user.getUserId();
//
//        OrderDao orderDao = new OrderDao();
//        String orderId = orderDao.createorder(userId.toString(), productId);
//
//
//        req.getRequestDispatcher("/").forward(req, resp);

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");


        CartDao cartDao = new CartDao();
        AddrDao addrDao = new AddrDao();
        ProductDao productDao = new ProductDao();
        String productId = req.getParameter("productId");

        Product product = productDao.findByProductId(Integer.parseInt(productId));
        Cart cart = new Cart(Integer.parseInt(productId), user.getUserId(),
                1, product.getPrice());
        cart.setProduct(product);


        //不需要添加到购物车
//        cartDao.addCart(cart);

        List<Cart> carts = new ArrayList<>();
        carts.add(cartDao.getcart(productId));
        List<Address> addrs = addrDao.selectAddr(user.getUserId());

        req.setAttribute("cartList", carts);
        req.setAttribute("addrList", addrs);
        req.setAttribute("msg", "直接购买");
        req.setAttribute("productId", productId);
        req.getRequestDispatcher("/order.jsp").forward(req, resp);
    }
}